package com.yanqu.road.dao.impl.union;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UnionActivityDaoImpl extends TempDataObjectDao<UnionActivityConditionData> {

    public Map<String, UnionActivityConditionData> getUnionActivityConditionDataMap(int activityId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, UnionActivityConditionData> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_union_activity_condition where activityId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                UnionActivityConditionData data = parse(rs);
                dataMap.put(data.getUnionUid(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<String, UnionActivityConditionData> getUnionActivityConditionDataMap(int activityId,int conditionType) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, UnionActivityConditionData> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_union_activity_condition where activityId = ? and conditionType = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, conditionType);
            rs = call.executeQuery();
            while (rs.next()) {
                UnionActivityConditionData data = parse(rs);
                dataMap.put(data.getUnionUid(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected boolean addData(UnionActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_union_activity_condition(unionUid,activityId,conditionId,preValue,value,isGetReward,lastUpdateTime,"
                + "memberList,info,unionBaseInfo,conditionType,positionInfo) values (?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionUid());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getLastUpdateTime());
            call.setString(i++, StringUtils.listToString(data.getMemberUserIdList(), ","));
            call.setString(i++, data.getInfo());
            call.setString(i++, data.getUnionBaseInfoJsonStr());
            call.setInt(i++, data.getConditionType());
            call.setString(i++,data.getMemberPositionMapJsonStr());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UnionActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "update t_u_union_activity_condition set conditionId=?,preValue=?,value=?,isGetReward=?,lastUpdateTime=?,"
                + "memberList=?,info=?,unionBaseInfo=?,positionInfo=? where unionUid=? and activityId=? and conditionType = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getLastUpdateTime());
            call.setString(i++, StringUtils.listToString(data.getMemberUserIdList(), ","));
            call.setString(i++, data.getInfo());
            call.setString(i++, data.getUnionBaseInfoJsonStr());
            call.setString(i++,data.getMemberPositionMapJsonStr());
            call.setString(i++, data.getUnionUid());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionType());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UnionActivityConditionData parseData(ResultSet rs) throws SQLException {
        UnionActivityConditionData data = new UnionActivityConditionData();
        data.setUnionUid(rs.getString("unionUid"));
        data.setActivityId(rs.getInt("activityId"));
        data.setConditionId(rs.getInt("conditionId"));
        String value = rs.getString("value");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        value = rs.getString("preValue");
        if(!StringUtils.isNullOrEmpty(value)){
            data.setPreValue(new BigInteger(value));
        }
        data.setGetReward(rs.getBoolean("isGetReward"));
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        data.setConditionType(rs.getInt("conditionType"));
        data.setMemberUserIdList(StringUtils.stringToLongList(rs.getString("memberList"), ","));
        data.setInfo(rs.getString("info"));
        value = rs.getString("unionBaseInfo");
        if(null == value) {
            value = "";
        }
        UnionBaseInfo unionBaseInfo = JSON.parseObject(value, new TypeReference<UnionBaseInfo>() {});
        if(null != unionBaseInfo){
            data.setUnionBaseInfo(unionBaseInfo);
        }

        String position =  rs.getString("positionInfo");
        if(StringUtils.isNullOrEmpty(position)) {
            position = "{}";
        }
        HashMap<Long, Integer> positionMap = JSON.parseObject(position, new TypeReference<HashMap<Long, Integer>>() {
        });
        if(null != positionMap) {
            data.setMemberPositionMap(positionMap);
        }
        return data;
    }
}
